#include <asm-generic/errno-base.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main(int argc, char *argv[]) {
  key_t key = ftok(".", 1);
  if (key < 0) {
    perror("ftok fail");
    exit(-1);
  }

  int shm_id = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0666);
  if (shm_id < 0) {
    if (errno == EEXIST) {
      shm_id = shmget(key, 1024, 0666);
      if (shm_id < 0) {
        perror("shmget fail");
        exit(-1);
      }
    } else {
      perror("shmget fail");
      exit(-1);
    }
  }

  char *shm_buf = shmat(shm_id, NULL, 0);
  if (shm_buf == (void *)-1) {
    perror("shmat fail");
    exit(-1);
  }

  while (1) {
    printf("please input:");
    scanf("%s", shm_buf);
    if (!strcmp(shm_buf, "bye"))
      break;
  }
  
  sleep(1);
  shmdt(shm_buf);
  shmctl(shm_id,IPC_RMID,0);

  return 0;
}
